package com.ocom.netty.mj.util;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.text.DecimalFormat;

/**
 * 数据类型转换工具类
 * @author cyf
 *
 */
public class NumConvertUtil{


    /**
     * bytes 转16进制字符串
     * @param bArray
     * @return
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toLowerCase());
        }
        return sb.toString();
    }




    /**
     * 16进制字符串转bytes
     * @param hex
     * @return
     */
    public static byte[] hexStringToByte(String hex) {

        int len = 0;
        int num=0;

        //判断字符串的长度是否是两位
        if(hex.length()>=2){

            //判断字符喜欢是否是偶数
            len=(hex.length() / 2);
            num = (hex.length() % 2);

            if (num == 1) {
                hex = "0" + hex;
                len=len+1;
            }


        }else{

            hex = "0" + hex;
            len=1;


        }


        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;

    }


    private static int toByte(char c) {


        if (c >= 'a')
            return (c - 'a' + 10) & 0x0f;
        if (c >= 'A')
            return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;


    }


    /**
     * 16进制字符串转十进制int
     * @param HexString
     * @return
     */
    public static Integer HexStringToInt(String HexString) {

        int inJTFingerLockAddress = Integer.valueOf(HexString, 16);

        return inJTFingerLockAddress;
    }




    /**
     * 十进制int转16进制字符串
     * @param num
     * @return
     */
    public static String IntToHexString(int num) {

        String hexString = Integer.toHexString(num);

        return hexString;
    }

    /**
     * 十进制int转16进制字符串
     * @param num
     * @return
     */
    public static String IntToHexStringNum(int num,Integer length) {

        String hexString = Integer.toHexString(num);
        if(hexString.length()<length){
            StringBuilder stringBuilder=new StringBuilder(hexString);
            for (int i=0;i<(length-hexString.length());i++){
                stringBuilder.insert(0,"0");
            }
            return stringBuilder.toString();
        }

        return hexString;
    }


    /**
     * 十进制->补0的字符串
     */
    public static String IntLegth(Integer num,Integer length) {
        String str = num.toString();
        if(str.length()<length){
            StringBuilder stringBuilder=new StringBuilder(str);
            for (int i=0;i<(length-str.length());i++){
                stringBuilder.insert(0,"0");
            }
            return stringBuilder.toString();
        }
        return str;
    }

    /**
     * 16进制String转BCD
     * @param asc
     * @return
     */
    public static byte[] strToBcd(String asc) {
        int len = asc.length();
        int mod = len % 2;

        if (mod != 0) {
            asc = "0" + asc;
            len = asc.length();
        }

        byte abt[] = new byte[len];
        if (len >= 2) {
            len = len / 2;
        }

        byte bbt[] = new byte[len];
        abt = asc.getBytes();
        int j, k;

        for (int p = 0; p < asc.length()/2; p++) {
            if ( (abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
                j = abt[2 * p] - '0';
            } else if ( (abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
                j = abt[2 * p] - 'a' + 0x0a;
            } else {
                j = abt[2 * p] - 'A' + 0x0a;
            }

            if ( (abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
                k = abt[2 * p + 1] - '0';
            } else if ( (abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
                k = abt[2 * p + 1] - 'a' + 0x0a;
            }else {
                k = abt[2 * p + 1] - 'A' + 0x0a;
            }

            int a = (j << 4) + k;
            byte b = (byte) a;
            bbt[p] = b;
        }
        return bbt;
    }


    /**
     * String 类型数字转化为Double  保留置顶小数位(用于显示金额等。)
     * @param money
     * @param type  保留小数点位数  #.00保留两位  #.0保留一位  #保留整数
     * @return
     */
    public static String strToDouble(String money,String type){

        String toDouble= new DecimalFormat(type).format(Double.parseDouble(money));

        return toDouble;

    }


    public static ByteBuf strToByteBuf(String con){
//String con = "800101010102020020600505052115400241510022";
        if (con != null && !con.equals("")){
            //调用下面的String转byte[]数组方法
            byte[] bytes = hexStringToByte(con);
            ByteBuf buf = Unpooled.wrappedBuffer(bytes);
            return buf;
        }
        return null;
    }

    /**
     * int到byte[] 由高位到低位
     * @param i 需要转换为byte数组的整行值。
     * @return byte数组
     */
    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
    }


    public static String byteToHex(Integer... params) {
        StringBuilder builder = new StringBuilder();
        for (Integer s : params) {
            int v = s & 0xFF;
            String colorHex=Integer.toHexString(v);
            if (1 == colorHex.length()) {
                builder.append('0');
            }
            builder.append(colorHex);
        }
        return  builder.toString();
    }

    public static String byteToHex(byte... params) {
        StringBuilder builder = new StringBuilder();
        for (Byte s : params) {
            int v = s & 0xFF;
            String colorHex=Integer.toHexString(v);
            if (1 == colorHex.length()) {
                builder.append('0');
            }
            builder.append(colorHex);
        }
        return  builder.toString();
    }


    public static String hexYihuo(String content) {
        content = change(content);
        String[] b = content.split(" ");
        int a = 0;
        for (int i = 0; i < b.length; i++) {
            a = a ^ Integer.parseInt(b[i], 16);
        }
        if(a<10){
            StringBuffer sb = new StringBuffer();
            sb.append("0");
            sb.append(a);
            return sb.toString();
        }
        return Integer.toHexString(a);
    }

    public static String change(String content) {
        String str = "";
        for (int i = 0; i < content.length(); i++) {
            if (i % 2 == 0) {
                str += " " + content.substring(i, i + 1);
            } else {
                str += content.substring(i, i + 1);
            }
        }
        return str.trim();
    }

    public static String hexLeijia(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
//            System.out.println(s);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }/*** 用256求余最大是255，即16进制的FF */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length(); // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static String reverseHex(final String hex) {
        final char[] charArray = hex.toCharArray();
        final int length = charArray.length;
        final int times = length / 2;
        for (int c1i = 0; c1i < times; c1i += 2) {
            final int c2i = c1i + 1;
            final char c1 = charArray[c1i];
            final char c2 = charArray[c2i];
            final int c3i = length - c1i - 2;
            final int c4i = length - c1i - 1;
            charArray[c1i] = charArray[c3i];
            charArray[c2i] = charArray[c4i];
            charArray[c3i] = c1;
            charArray[c4i] = c2;
        }
        return new String(charArray);
    }


    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

    public static String binaryString2hexString(String bString) {
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)
            return null;
        StringBuffer tmp=new StringBuffer();
        int iTmp = 0;
        for (int i = 0; i < bString.length(); i += 4) {
            iTmp = 0;
            for (int j = 0; j < 4; j++) {
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
            }
            tmp.append(Integer.toHexString(iTmp));
        }
        return tmp.toString();
    }


    /**
     * 16进制转换成为string类型字符串
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }


    public static void main(String[] args){

        System.out.println( hexStringToString("5665723a362e322e3530"));

        System.out.println( IntToHexStringNum(10,2));
        System.out.println( reverseHex(IntToHexStringNum(10,8)));

        String timeBit="1234000000000000";
        StringBuilder stringBuilder1=new StringBuilder(timeBit);
        System.out.println(stringBuilder1.substring(2,4));

        System.out.println(hexString2binaryString("0300"));
        System.out.println(binaryString2hexString("0000001100000000"));

        //16转10
        Integer b=Integer.parseInt("104c",16);
        System.out.println(b);

        //10转16
        String s=Integer.toHexString(b);
        System.out.println(s);


        //byte 转 16进制
        System.out.println(byteToHex(-84,-54));

//caac004c010221120004013ff00148000000000001003100000000000000000a5665723a362e322e353000000000000000000000000000000000000000000000000000000000000019a2a97044284ca9acca

        byte[] bytes1=HexUtil.decodeHex("0102211200040130000001000000000001003100000000000000000a5665723a362e322e3530000000000000000000000000000000000000000000000000000000000000");

        System.out.println(hexYihuo("0102211200040130000001000000000001003100000000000000000a5665723a362e322e3530000000000000000000000000000000000000000000000000000000000000"));
        System.out.println(hexLeijia("0102211200040130000001000000000001003100000000000000000a5665723a362e322e3530000000000000000000000000000000000000000000000000000000000000"));



        System.out.println(HexUtil.decodeHex("4c"));
    }

}
